package com.wxapp.common.util.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * @author lgl
 * @Description
 * @Datetime 2023/6/1 15:54
 * @Modified By
 */
@Component
public class RedissonUtil {
    private static final Logger log = LoggerFactory.getLogger(RedissonUtil.class);

    private static RedissonClient redissonClient;

    public RedissonUtil(RedissonClient redissonClient) {
        RedissonUtil.redissonClient = redissonClient;
    }

    public static boolean tryLock(String lockKey) {
        return  tryLock( lockKey, 15L, null, TimeUnit.SECONDS);
    }


    public static boolean tryLock(String lockKey, Long waitTime, Long leaseTime, TimeUnit unit)  {
        var lock = getLock(lockKey);
        try {
            // 锁15秒后自动释放，防止死锁
            if (leaseTime==null){
                return  lock.tryLock(waitTime, unit);
            }
            return  lock.tryLock(waitTime, leaseTime, unit);
        } catch (Exception e) {
            lock.unlock();
            log.error("DistributedRedisLock lock [{}] Exception:", lockKey, e);
            return false;
        }
    }
    public static boolean lock(String lockKey, long time) throws InterruptedException {
        var lock = getLock(lockKey);
        try{
            if ( !lock.isLocked()){
                // 锁15秒后自动释放，防止死锁
                lock.lock(time, TimeUnit.SECONDS);
                log.info("Thread [{}] DistributedRedisLock lock [{}] success", Thread.currentThread().getName(), lockKey);
                // 加锁成功
                return true;
            }
            return false;
        } catch (Exception e) {
            lock.unlock();
            log.error("DistributedRedisLock lock [{}] Exception:", lockKey, e);
            return false;
        }
    }

    public static boolean isLocked(String lockKey) {
        var lock = getLock(lockKey);
        try {
            return lock.isLocked();
        } catch (Exception e) {
            lock.unlock();
            log.error("DistributedRedisLock lock [{}] Exception:", lockKey, e);
            return false;
        }
    }

    public static void unLock(String lockKey) {
         var lock = getLock(lockKey);
        try {
            lock.unlock();
            log.info("Thread [{}] DistributedRedisLock unlock [{}] success", Thread.currentThread().getName(), lockKey);
            // 释放锁成功
        } catch (Exception e) {
            lock.unlock();
            log.error("DistributedRedisLock unlock [{}] Exception:", lockKey, e);
        }
    }
    private static RLock getLock(String lockKey){
        return redissonClient.getLock(lockKey);
    }
}
